import { request } from '@/utils/request'
import type { WorkflowNode, WorkflowEdge, ExecutionResult } from '@/types/workflow'

export class ExecutorService {
    private static instance: ExecutorService
    private executingTasks: Map<string, AbortController>

    private constructor() {
        this.executingTasks = new Map()
    }

    static getInstance() {
        if (!ExecutorService.instance) {
            ExecutorService.instance = new ExecutorService()
        }
        return ExecutorService.instance
    }

    // 执行工作流
    async executeWorkflow(
        workflowId: string,
        nodes: WorkflowNode[],
        edges: WorkflowEdge[],
        params: Record<string, any>
    ): Promise<ExecutionResult> {
        const abortController = new AbortController()
        this.executingTasks.set(workflowId, abortController)

        try {
            const response = await request.post(
                `/workflows/${workflowId}/execute`,
                {
                    nodes,
                    edges,
                    params
                },
                {
                    signal: abortController.signal,
                    timeout: 3600000 // 1小时超时
                }
            )

            this.executingTasks.delete(workflowId)
            return response.data
        } catch (error) {
            this.executingTasks.delete(workflowId)
            throw error
        }
    }

    // 取消执行
    cancelExecution(workflowId: string) {
        const controller = this.executingTasks.get(workflowId)
        if (controller) {
            controller.abort()
            this.executingTasks.delete(workflowId)
        }
    }

    // 获取执行状态
    async getExecutionStatus(executionId: string) {
        const response = await request.get(`/executions/${executionId}`)
        return response.data
    }

    // 获取执行历史
    async getExecutionHistory(workflowId: string) {
        const response = await request.get(`/workflows/${workflowId}/executions`)
        return response.data
    }

    // 重试执行
    async retryExecution(executionId: string) {
        const response = await request.post(`/executions/${executionId}/retry`)
        return response.data
    }

    // 批量执行
    async batchExecute(
        workflowId: string,
        paramsList: Record<string, any>[]
    ) {
        const response = await request.post(`/workflows/${workflowId}/batch-execute`, {
            paramsList
        })
        return response.data
    }

    // 获取执行进度
    async getExecutionProgress(executionId: string) {
        const response = await request.get(`/executions/${executionId}/progress`)
        return response.data
    }

    // 获取执行日志
    async getExecutionLogs(executionId: string) {
        const response = await request.get(`/executions/${executionId}/logs`)
        return response.data
    }
}

// 导出单例实例
export const executor = ExecutorService.getInstance() 